<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2007 Dmitry Dulepov <dmitry@typo3.org>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*  A copy is found in the textfile GPL.txt and important notices to the license
*  from the author is found in LICENSE.txt distributed with these scripts.
*
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * Hooks for tt_news frontend plugin to enable displaying most read items.
 *
 * $Id: $
 *
 * @author	Dmitry Dulepov <dmitry@typo3.org>
 */
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 */

/**
 * This clas contains hooks for tt_news frontend plugin to enable displaying most read items.
 *
 * @author	Dmitry Dulepov <dmitry@typo3.org>
 * @package TYPO3
 * @subpackage nc_ttnews_mostpopular
 */
class tx_ncttnewsmostpopular_hooks {

	protected $ignoreUserAgents = array(
		'/AltaVista/i',
		'/crawler/i',
		'/curl/i',
		'/geckobot/i',
		'/Googlebot/i',
		'/ia_archiver/i',
		'/libwww-perl/i',
		'/Lycos_Spider/i',
		'/mnoGoSearch/i',
		'/Slurp/i',
		'/Scooter/i',
		'/Spyder/i',
		'/wget/i',
		'/Yandex/i',
	);

	/**
	 * Updates $selectConf if current code is MOST_POPULAR to fetch mostly read objects.
	 * Function alters $selectConf['orderBy'] entry and sets it to tx_ncttnewsmostpopular_counter if
	 * $pObj->theCode is MOST_POPULAR.
	 *
	 * @param	tx_ttnews	$pObj	Parent object
	 * @param	array	$selectConf	Configuration array as required by {@link tslib_cObj::exec_getQuery()}
	 * @see	tx_ttnews::getSelectConf()
	 * @see	tslib_cObj::exec_getQuery()
	 * @see http://bugs.typo3.org/view.php?id=6884
	 */
	function processSelectConfHook(&$pObj, &$selectConf) {
		/* @var $pObj tx_ttnews */
		if ($pObj->theCode == 'MOST_POPULAR') {
			$oldOrderBy = trim($selectConf['orderBy']);
			if (!$oldOrderBy) {
				$oldOrderBy = trim($pObj->config['orderBy']);
				if ($oldOrderBy && trim($this->config['ascDesc'])) {
					$oldOrderBy .= ' ' . $this->config['ascDesc'];
				}
			}
			// tt_news overrides our selection of orderBy, so we have to tweak that again
			$pObj->config['orderBy'] = $selectConf['orderBy'] = 'tx_ncttnewsmostpopular_counter DESC' . ($oldOrderBy ? ',' . $oldOrderBy : '');
			$this->config['ascDesc'] = '';
			if ($selectConf['limit'] == '' && $pObj->config['limit']) {
				$selectConf['limit'] = $pObj->config['limit'];
			}
			$selectConf['begin'] =0;
		}
		return $selectConf;
	}

	/**
	 * Processes custom codes.
	 * If code is MOST_POPULAR, executes {@link tx_ttnews::displayList()} function of the parent object ($pObj).
	 * Without this hook tt_news will not know what to do with our custom code.
	 *
	 * @param	tx_ttnews	$pObj	Parent object
	 * @return	string	Generated content
	 * @see	tx_ttnews::main_news()
	 */
	function extraCodesProcessor(&$pObj) {
		/* @var $pObj tx_ttnews */
		return ($pObj->theCode == 'MOST_POPULAR' ? $pObj->displayList() : '');
	}

	/**
	 * Checks if tt_news is displaying a single news item and updates item display counter.
	 * This function hooks to TSFE's content output. It does not really do anything
	 * with output but this is the only way to avoid extra plugin. Function is called for
	 * cached and non-cached content. Implementation is made as much effective as possible (using
	 * PHP language constructs to check that variable is present before using it) to ensure
	 * minimal impact on perfomance. Cache is cleared if necessary
	 *
	 * @param	array	$params	Unused (parameters)
	 * @param	tslib_fe	$pObj	Unused (parent object)
	 * @see	tslib_fe::processOutput()
	 * @todo Clear cache?
	 */
	function contentPostProcOutput(&$params, &$pObj) {
		$ttnews_piVars = t3lib_div::_GP('tx_ttnews');
		if (is_array($ttnews_piVars)) {

			foreach ($this->ignoreUserAgents as $agent) {
				if (preg_match($agent, $_SERVER['HTTP_USER_AGENT'])) {
					return;
				}
			}

			if (isset($ttnews_piVars['tt_news']) && t3lib_div::testInt($ttnews_piVars['tt_news'])) {
				$GLOBALS['TYPO3_DB']->sql_query('UPDATE tt_news SET tx_ncttnewsmostpopular_counter=tx_ncttnewsmostpopular_counter+1 WHERE uid=' . intval($ttnews_piVars['tt_news']));
			}
			if (isset($ttnews_piVars['backPid']) && t3lib_div::testInt($ttnews_piVars['backPid'])) {
				require_once(PATH_t3lib . 'class.t3lib_tcemain.php');
				// Create TCEmain and clear cache
				$tce = t3lib_div::makeInstance('t3lib_TCEmain');
				/* @var $tce t3lib_TCEmain */
				$tce->clear_cacheCmd(intval($ttnews_piVars['backPid']));
			}
		}
	}

	/**
	 * Processes comments-specific markers for tt_news
	 *
	 * @param	array		$markerArray	Array with merkers
	 * @param	array		$row	tt_news record
	 * @param	array		$lConf	Configuration array for current tt_news view
	 * @param	tx_ttnews	$pObj	Reference to parent object
	 * @return	array		Modified marker array
	 */
	public function extraItemMarkerProcessor(&$markerArray, &$row, &$lConf, &$pObj) {
		/* @var $pObj tx_ttnews */
		$template = array(
						$pObj->cObj->getSubpart($pObj->templateCode, '###TX_NCTTNEWSMOSTPOPULAR_NOT_VIEWED###'),
						$pObj->cObj->getSubpart($pObj->templateCode, '###TX_NCTTNEWSMOSTPOPULAR_VIEWED###'),
					);
		if ($template) {
			$cObj = t3lib_div::makeInstance('tslib_cObj');
			/* @var $cObj tslib_cObj */
			$cObj->start(array());
			$conf = array(
				'includeLibs' => 'EXT:nc_ttnews_mostpopular/class.tx_ncttnewsmostpopular_hooks.php',
				'userFunc' => 'tx_ncttnewsmostpopular_hooks->showNewsCounter',
				'template' => $template,
				'uid' => $row['uid'],
			);
			$markerArray['###TX_NCTTNEWSMOSTPOPULAR###'] = $cObj->cObjGetSingle('USER_INT', $conf);
		}
		return $markerArray;
	}

	public function showNewsCounter($content, $conf) {
		t3lib_div::loadTCA('tt_news');
		$rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('tx_ncttnewsmostpopular_counter', 'tt_news',
						'uid=' . $conf['uid'] . $this->cObj->enableFields('tt_news'));
		if (count($rows)) {
			$count = $rows[0]['tx_ncttnewsmostpopular_counter'];
			return $this->cObj->substituteMarker($conf['template'][$count ? 1 : 0],
							'###COUNT###', $count);
		}
	}
}

if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/nc_ttnews_mostpopular/class.tx_ncttnewsmostpopular_hooks.php']) {
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/nc_ttnews_mostpopular/class.tx_ncttnewsmostpopular_hooks.php']);
}

?>